<template>
  <view class="container">
    <!-- 图表容器 -->
    <view 
      :class="['chart-container', isFullScreen ? 'full-screen' : '']"
      @touchstart="handleTouchStart"
      @touchend="handleTouchEnd"
	  @touchmove.prevent 
    >
      <l-echart ref="chartRef"></l-echart>
      <view class="fullscreen-tip" v-if="!isFullScreen">双击图表全屏显示</view>
      <view class="exit-fullscreen" v-if="isFullScreen" @click.stop="toggleFullScreen">
        <text class="iconfont icon-close"></text>
      </view>
    </view>
    
    <!-- 添加体温表单 - 全屏时隐藏 -->
    <view class="form-container" v-if="!isFullScreen">
      <view class="form-item">
        <text>日期</text>
        <picker mode="date" fields="day" :value="formData.date" @click.stop @change="onDateChange">
          <text>{{ formData.date || '选择日期' }}</text>
        </picker>
      </view>
      <view class="form-item">
        <text>体温</text>
        <input type="number" v-model="formData.temperature" placeholder="输入体温" @click.stop />
        <text>°C</text>
      </view>
      <view class="form-item">
        <text>事件</text>
        <picker mode="selector" :range="eventOptions" range-key="name" @click.stop @change="oneventChange">
          <text>{{ formData.typeId ? eventOptions.find(r => r.id === formData.typeId)?.name : '选择事件' }}</text>
        </picker>
      </view>
      <view class="form-item">
        <text>备注</text>
        <input type="text" v-model="formData.comment" placeholder="输入备注(没有可填无)" @click.stop />
      </view>
      <button @click.stop="addTemperatureRecord">添加记录</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getAllTypes, addPoint, getPoints, download } from '@/api/temperature.js';
const echarts = require('../../uni_modules/lime-echart/static/echarts.min')

// 图表引用
const chartRef = ref(null)

// 全屏状态
const isFullScreen = ref(false)

// 双击检测相关变量
const lastTapTime = ref(0)
const tapTimeout = ref(null)

// 月经周期数据
const menstrualCycles = ref([])

// 备注选项
const eventOptions = ref([])

// 表单数据
const formData = ref({
  date: '',
  temperature: '',
  typeId: '',
  comment: ''
})

// 温度记录数据
const temperatureRecords = ref([])

// 处理触摸开始事件
const handleTouchStart = () => {
  clearTimeout(tapTimeout.value)
}

// 处理触摸结束事件（实现双击检测）
const handleTouchEnd = () => {
  const currentTime = Date.now()
  const tapLength = currentTime - lastTapTime.value
  if (tapLength < 300 && tapLength > 0) {
    // 双击事件
    clearTimeout(tapTimeout.value)
    toggleFullScreen()
  } else {
    // 单击事件
    tapTimeout.value = setTimeout(() => {
      // 这里可以添加单击事件的处理
    }, 300)
  }
  lastTapTime.value = currentTime
}

// 切换全屏状态
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value
  if (isFullScreen.value) {
    uni.showToast({
      title: '请旋转设备横屏查看',
      icon: 'none',
      duration: 2000
    })
  }
  setTimeout(() => {
    initChart()
  }, 100)
}

// 识别月经周期
const identifyMenstrualCycles = () => {
  const cycles = []
  let currentCycle = null
  
  // 按日期排序
  const sortedRecords = [...temperatureRecords.value].sort((a, b) => new Date(a.date) - new Date(b.date))

  sortedRecords.forEach(record => {
    if (record.typeName === '月经开始') {
      // 如果已经有未结束的周期，先结束它
      if (currentCycle) {
        currentCycle.endDate = record.date
        cycles.push(currentCycle)
      }
      // 开始新周期
      currentCycle = {
        startDate: record.date,
        endDate: null,
        records: [record]
      }
    } else if (currentCycle) {
      currentCycle.records.push(record)
    }
  })
  
  // 添加最后一个未结束的周期
  if (currentCycle) {
    cycles.push(currentCycle)
  }
  
  menstrualCycles.value = cycles
}

// 初始化图表
const initChart = async () => {
if (!chartRef.value || menstrualCycles.value.length === 0) return
  const myChart = await chartRef.value.init(echarts)
  
  // 准备所有周期的数据
  const allDates = []
  const allTemperatures = []
  const allPhases = []
  const allRecords = []
  const cycleBoundaries = []
  
  let dayCount = 0
  
  // 处理所有周期数据
  menstrualCycles.value.forEach((cycle, cycleIndex) => {
    // 确保cycle.records存在且是数组
    const records = Array.isArray(cycle.records) ? cycle.records : []
    
    // 计算周期阶段
    let menstrualPhaseEnd = null
    let follicularPhaseEnd = null
    
    // 找出月经结束和排卵日
    const periodEndRecord = records.find(r => r?.typeName === '月经结束')
    const ovulationRecord = records.find(r => r?.typeName === '排卵日')
    
    if (periodEndRecord) menstrualPhaseEnd = new Date(periodEndRecord.date)
    if (ovulationRecord) follicularPhaseEnd = new Date(ovulationRecord.date)
    
    // 添加周期边界标记

      cycleBoundaries.push({
        cycleIndex,
        startIndex: dayCount
      })
    
    
    // 添加当前周期的数据
    records.forEach(record => {
      if (!record?.date || record?.temperature === undefined) return
      
      const recordDate = new Date(record.date)
      allDates.push(`${recordDate.getMonth() + 1}月${recordDate.getDate()}日`)
      allTemperatures.push(record.temperature)
      allRecords.push(record)

      // 确定阶段
      let phase = '未知'
      if (record.typeName === '月经开始' || record.typeName === '月经结束') {
        phase = '月经期'
      } else if (periodEndRecord && ovulationRecord) {
        if (recordDate <= menstrualPhaseEnd) {
          phase = '月经期'
        } else if (recordDate <= follicularPhaseEnd) {
          phase = '卵泡期'
        } else {
          phase = '黄体期'
        }
      } else if (periodEndRecord && !ovulationRecord) {
        phase = recordDate <= menstrualPhaseEnd ? '月经期' : '卵泡期'
      } else if (!periodEndRecord && ovulationRecord) {
        phase = recordDate <= follicularPhaseEnd ? '月经期' : '黄体期'
      } else {
        phase = '月经期'
      }
      
      allPhases.push(phase)
      dayCount++
    })
  })
  // 准备分段数据
  const pieces = []
  let startIndex = 0
  let currentPhase = allPhases[0] || '未知'
  
  // 生成分段数据
  for (let i = 1; i < allPhases.length; i++) {
    if (allPhases[i] !== currentPhase) {
      pieces.push({
        gt: startIndex - 0.5,
        lte: i - 0.5,
        color: getColorByPhase(currentPhase)
      })
      startIndex = i
      currentPhase = allPhases[i]
    }
  }
  
  // 添加最后一段
  if (allPhases.length > 0) {
    pieces.push({
      gt: startIndex - 0.5,
      lte: allPhases.length - 0.5,
      color: getColorByPhase(currentPhase)
    })
  }

  // 添加周期分隔线
  const markLineData = cycleBoundaries.map(boundary => ({
    xAxis: boundary.startIndex - 0.5,
    lineStyle: {
      color: '#999',
      type: 'dashed',
      width: 2
    },
    label: {
      formatter: `周期 ${boundary.cycleIndex + 1}`,
      position: 'end',
	  rotate: 0,
    }
  }))

  const option = {
    title: {
      text: '基础体温曲线图 - 全部周期',
      left: 'center'
    },
    tooltip: {
       trigger: 'item', // 只在数据项上触发
       showContent: true,
       // 添加以下配置限制触发条件
       position: function(point, params, dom, rect, size) {
         // 只在实际数据点附近显示
         return [point[0], point[1]];
       },
       // 确保只在数据点上触发
       confine: true,
       // 添加formatter的安全检查
       formatter: function(params) {
         if (!params.data || !params.data.value) {
           return '';
         }
         const record = allRecords[params.dataIndex];
         if (!record) return '';
         
         const phase = allPhases[params.dataIndex] || '未知';
         let tip = `日期: ${record.date} 体温: ${record.temperature}°C 阶段: ${phase}`;
         if (record.typeName !== '正常') {
           tip += ` 事件: ${record.typeName}`;
         }
         if (record.comment && record.comment !== '无') {
           tip += ` 备注: ${record.comment}`;
         }
         return tip;
       }
     },
    xAxis: {
      type: 'category',
      data: allDates,
      name: '日期',
      axisLabel: {
        interval: 0,
        rotate: 45
      },
      axisPointer: {
        show: true
      }
    },
    yAxis: {
      type: 'value',
      name: '体温(°C)',
      min: 36,
      max: 38
    },
    dataZoom: [
      {
        type: 'slider',
        show: false,
        xAxisIndex: [0],
        start: 0,
        end: 70,
        handleSize: 8
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 0,
        end: 100
      }
    ],
    visualMap: {
      type: 'piecewise',
      show: false,
      dimension: 0,
      pieces: pieces,
      outOfRange: {
        color: '#D25991'
      }
    },
    series: [
      {
        name: '体温',
        type: 'line',
        symbol: 'circle',
        symbolSize: '10',
        data: allTemperatures.map((temp, index) => {
          const record = allRecords[index]
          return {
            value: temp,
            symbol: getSymbolByType(record.typeName),
            symbolSize: 10,
            itemStyle: { color: getColorByType(record.typeName) },
          }
        }),
        lineStyle: {
          width: 3
        },
        markLine: {
          symbol: 'none',
          silent: true,
          data: markLineData
        }
      }
    ],
    legend: {
      data: ['月经期', '卵泡期', '黄体期'],
      selected: {
        '月经期': true,
        '卵泡期': true,
        '黄体期': true
      }
    }
  }

  myChart.setOption(option)
  
  // 自适应大小
  myChart.resize()
}

// 根据阶段获取颜色
const getColorByPhase = (phase) => {
  switch(phase) {
    case '月经期': return '#c63c6d'
    case '卵泡期': return '#9fd8ff'
    case '黄体期': return '#ffd59f'
    default: return '#cccccc'
  }
}

// 根据类型获取颜色
const getColorByType = (typeName) => {
  switch(typeName) {
    case '月经开始': return '#c62a2a'
    case '月经结束': return '#c62a2a'
    case '排卵日': return '#7777ff'
    case '正常': return '#ff7139'
    default: return '#1f1ff9'
  }
}

// 根据类型获取符号
const getSymbolByType = (typeName) => {
  switch(typeName) {
    case '月经开始': return 'rect'
    case '月经结束': return 'triangle'
    case '排卵日': return 'diamond'
    case '正常': return 'circle'
    default: return 'roundRect'
  }
}

// 日期变化处理
const onDateChange = (e) => {
  formData.value.date = e.detail.value
}

// 备注变化处理
const oneventChange = (e) => {
  formData.value.typeId = eventOptions.value[e.detail.value].id
}

// 添加体温记录
const addTemperatureRecord = async () => {
  if (!formData.value.date || !formData.value.temperature || !formData.value.typeId) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  
  try {
    const res = await addPoint({
      temperature: parseFloat(formData.value.temperature),
      typeId: formData.value.typeId,
      date: formData.value.date,
      comment: formData.value.comment || '无'
    })
    
    if (res.code === '200') {
      uni.showToast({
        title: '记录添加成功',
        icon: 'success'
      })
      // 重新加载数据
      loadTemperatureRecords()
      formData.value.temperature = ''
      formData.value.comment = ''
    } else {
      uni.showToast({
        title: res.msg || '添加失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '添加失败，请重试',
      icon: 'none'
    })
    console.error('添加记录失败:', error)
  }
}

// 加载备注类型
const loadeventTypes = async () => {
  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  try {
    const res = await getAllTypes()
    if (res.code === '200') {
      eventOptions.value = res.data
      // 设置默认类型
      if (res.data.length > 0) {
        formData.value.typeId = res.data[0].id
      }
      uni.hideLoading()
    }
  } catch (error) {
    console.error('加载备注类型失败:', error)
    uni.hideLoading()
  }
}

// 加载温度记录
const loadTemperatureRecords = async () => {
  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  try {
    const res = await getPoints({ cycle: '0' })
    if (res.code === '200') {
      // 处理嵌套数组结构，将所有数据合并到一个数组中
      temperatureRecords.value = res.data.flat()
      identifyMenstrualCycles()
      initChart()
    }
    uni.hideLoading()
  } catch (error) {
    console.error('加载记录失败:', error)
    uni.hideLoading()
  }
}

// 初始化
onMounted(() => {
  const today = new Date()
  formData.value.date = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
  
  // 加载备注类型
  loadeventTypes().then(() => {
    // 加载温度记录
    loadTemperatureRecords()
  })
})
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #F8F5FF;
  height: 100vh;
}

/* 图表容器样式 */
.chart-container {
  position: relative;
  width: 750rpx;
  height: 700rpx;
  background-color: #fff;
  transition: all 0.3s ease;
  /* 全屏状态下的样式 */
  &.full-screen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 999;
    background-color: #fff;
  }
  
  /* 全屏提示 */
  .fullscreen-tip {
    position: absolute;
    bottom: 20rpx;
    left: 0;
    right: 0;
    text-align: center;
    color: #999;
    font-size: 24rpx;
  }
  
  /* 退出全屏按钮 */
  .exit-fullscreen {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    
    .iconfont {
      color: white;
      font-size: 36rpx;
    }
  }
}

.form-container {
  width: 100%;
  margin-top: 40rpx;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    padding: 0rpx 20rpx;
    text {
      margin-right: 10rpx;
      &:first-child {
        width: 80rpx;
      }
    }
    
    input {
      flex: 1;
      text-align: right;
      padding: 10rpx;
      border-radius: 8rpx;
    }
    
    picker {
      flex: 1;
      padding: 10rpx;
      border-radius: 8rpx;
      text-align: right;
    }
  }
  
  button {
    width: 95%;
    margin-top: 20rpx;
    background-color: #D25991;
    color: white;
  }
}
</style>